<template>
  <div class="container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-row>
          <el-col :span="6">
            <el-form-item label="学生姓名">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入学生姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学号">
              <el-input
                v-model="searchForm.studentNumber"
                placeholder="请输入学号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleResetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 列表 -->
    <div class="common-layout-main">
      <div class="common-head">
        <el-button type="primary" @click="handleAdd">添加学生</el-button>
      </div>
      <el-table :data="students" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column
          prop="studentNumber"
          label="学号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="className"
          label="班级"
          width="120"
        ></el-table-column>
        <el-table-column prop="age" label="年龄" width="80"></el-table-column>
        <el-table-column
          prop="gender"
          label="性别"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="gmtCreate"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="gmtModified"
          label="修改时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:currentPage="pagination.pageNum"
        v-model="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 50, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchStudents"
        @current-change="fetchStudents"
      />
    </div>

    <!-- 编辑/添加弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="ruleFormRef" :model="student" :rules="rules">
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="student.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="学号"
          :label-width="formLabelWidth"
          prop="studentNumber"
        >
          <el-input
            v-model="student.studentNumber"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
          <el-input v-model="student.age" type="number"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
          <el-select v-model="student.gender">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" :label-width="formLabelWidth" prop="classId">
          <el-select v-model="student.classId" placeholder="请选择班级">
            <el-option
              v-for="item in classOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit(ruleFormRef)"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { getClassList } from "@/api/class";
import {
  getStudentList,
  getStudentById,
  deleteStudent,
  createStudent,
  updateStudent,
} from "@/api/student";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";

interface Student {
  id: string;
  name: string;
  studentNumber: string;
  age: number | null;
  gender: string;
}

interface SearchForm {
  name: string | null;
  studentNumber: string | null;
}

interface Pagination {
  pageNum: number;
  pageSize: number;
  total: number;
}

const students = ref<Student[]>([]);
const student = reactive<Student>({
  id: "",
  name: "",
  studentNumber: "",
  age: null,
  gender: "",
});
const searchForm = reactive<SearchForm>({
  name: null,
  studentNumber: null,
});
const pagination = reactive<Pagination>({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formLabelWidth = "120px";
const ruleFormRef = ref<FormInstance>();

const rules = reactive({
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  studentNumber: [{ required: true, message: "学号不能为空", trigger: "blur" }],
  age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
  gender: [{ required: true, message: "性别不能为空", trigger: "change" }],
});

const fetchStudents = async () => {
  try {
    const response = await getStudentList({
      ...searchForm,
      ...pagination,
    });
    students.value = response.data;
    pagination.total = response.total;
  } catch (error) {
    console.error("Error fetching students:", error);
  }
};

const handleAdd = () => {
  Object.assign(student, {
    id: "",
    name: "",
    studentNumber: "",
    age: null,
    gender: "",
  });
  dialogTitle.value = "添加学生";
  dialogVisible.value = true;
};

const handleEdit = async (row: Student) => {
  const { data } = await getStudentById(row.id);
  Object.assign(student, data);
  dialogTitle.value = "编辑学生";
  dialogVisible.value = true;
};

const handleDelete = async (id: Number) => {
  try {
    await ElMessageBox.confirm("是否删除该学生？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });
    await deleteStudent(id);
    fetchStudents();
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  } catch (error) {
    console.error("Error deleting student:", error);
  }
};

const handleSubmit = async (formEl: FormInstance | undefined) => {
  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      if (student.id) {
        try {
          await updateStudent(student);
          fetchStudents();
        } catch (error) {
          console.error("Error updating student:", error);
        }
      } else {
        try {
          await createStudent(student);
          fetchStudents();
        } catch (error) {
          console.error("Error creating student:", error);
        }
      }
      dialogVisible.value = false;
    } else {
      console.log("表单验证失败");
    }
  });
};

const handleSearch = () => {
  pagination.pageNum = 1;
  fetchStudents();
};

const handleResetSearch = () => {
  Object.assign(searchForm, { name: null, studentNumber: null });
  handleSearch();
};

interface ClassOption {
  id: string;
  className: string;
}

const classOptions = ref<ClassOption[]>([]); // 存储班级数据

const fetchClassOptions = async () => {
  try {
    const response = await getClassList({
      pageNum: 1,
      pageSize: 1000,
    }); // 调用远端接口获取班级数据
    classOptions.value = response.data;
  } catch (error) {
    console.error("获取班级数据失败", error);
  }
};

onMounted(() => {
  fetchClassOptions(); // 组件加载时获取班级数据
});

onMounted(() => {
  fetchStudents();
});
</script>

<style lang="scss" scoped>
.container {
  .search-form {
    background: #fff;
    padding: 15px 10px 0;
    margin-bottom: 10px;
  }
  .common-layout-main {
    background-color: #fff;
    padding: 15px 10px 0;
  }
}
</style>
